﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Himp.DataHub
{
    /// <summary>
    /// 药品目录扩展信息
    /// </summary>
    public class DrugCatalogExtService : CrudAppService<DrugCatalogExt, DrugCatalogExtDto, Guid, DrugCatalogExtInput, DrugCatalogExtCreateOrUpdateDto, DrugCatalogExtCreateOrUpdateDto>, IDrugCatalogExtService
    {
        private IRepository<DrugCatalogExt, Guid> _DrugCatalogExtRepository;
        private IDrugPrdrService _drugPrdrService;

        public DrugCatalogExtService(IRepository<DrugCatalogExt, Guid> DrugCatalogExtRepository
            , IDrugPrdrService drugPrdrService) : base(DrugCatalogExtRepository)
        {
            _DrugCatalogExtRepository = DrugCatalogExtRepository;
            _drugPrdrService = drugPrdrService;
        }

        /// <summary>
        /// 获取药品目录扩展信息列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<DrugCatalogExtDto>> GetListAsync(DrugCatalogExtInput input)
        {
            var iQuery = await _DrugCatalogExtRepository.GetQueryableAsync();
            iQuery = iQuery.WhereIf(input.DrugCatalogId != null, i => i.DrugCatalogId == input.DrugCatalogId);

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<DrugCatalogExt>, List<DrugCatalogExtDto>>(iQuery.ToList());

                return new PagedResultDto<DrugCatalogExtDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<DrugCatalogExt>, List<DrugCatalogExtDto>>(items.ToList());

                return new PagedResultDto<DrugCatalogExtDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 创建药品目录扩展信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<DrugCatalogExtDto> CreateAsync(DrugCatalogExtCreateOrUpdateDto input)
        {
            var drugPrdr = await _drugPrdrService.GetAsync(input.DrugPrdrId);
            input.DrugPrdr = new DrugPrdrCreateDto()
            {
                PrdrName = drugPrdr.PrdrName
            };

            return await base.CreateAsync(input);
        }
    }
}
